<script setup>
import { reactive, ref, onMounted } from 'vue';
import { ElMessage, ElDialog, ElForm, ElFormItem, ElInput, ElUpload, ElButton, ElSelect, ElOption } from 'element-plus'
import { useRouter } from 'vue-router'
import { User, Lock, Key, ArrowRight } from '@element-plus/icons-vue'
import loginApi from '../api/login_api.js'
import api from '../api/user_api.js'

// 忘记密码相关变量
const forgetPwdDialogVisible = ref(false);
const forgetPwdObj = ref({
  email: '',
  code: '',
  newPassword: '',
  confirmPassword: ''
});
const forgetPwdFormRef = ref(null);
const codeCountdown = ref(0);
const codeTimer = ref(null);

// 忘记密码表单验证规则
const forgetPwdRules = ref({
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/, message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 6, max: 6, message: '验证码长度为6位', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度需在6-20位之间', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== forgetPwdObj.value.newPassword) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
});

// 打开忘记密码弹窗
const openForgetPwdDialog = () => {
  forgetPwdObj.value = {
    email: '',
    code: '',
    newPassword: '',
    confirmPassword: ''
  };
  forgetPwdDialogVisible.value = true;
  if (codeTimer.value) {
    clearInterval(codeTimer.value);
    codeCountdown.value = 0;
  }
};

// 发送验证码
const sendVerificationCode = async () => {
  if (!forgetPwdObj.value.email) {
    ElMessage.warning('请输入邮箱');
    return;
  }

  // 验证邮箱格式
  const emailReg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
  if (!emailReg.test(forgetPwdObj.value.email)) {
    ElMessage.warning('请输入正确的邮箱格式');
    return;
  }

  try {
    // 调用发送验证码API
    await loginApi.sendCode(forgetPwdObj.value.email);
    ElMessage.success('验证码已发送，请注意查收');

    // 开始倒计时
    codeCountdown.value = 60;
    codeTimer.value = setInterval(() => {
      codeCountdown.value--;
      if (codeCountdown.value <= 0) {
        clearInterval(codeTimer.value);
        codeCountdown.value = 0;
      }
    }, 1000);
  } catch (error) {
    ElMessage.error(error.message || '发送验证码失败');
  }
};

// 确认重置密码
const confirmResetPwd = async () => {
  if (!forgetPwdFormRef.value) return;

  forgetPwdFormRef.value.validate(async (valid) => {
    if (!valid) return;

    try {
      // 调用重置密码API
      await loginApi.resetByEmail({
        email: forgetPwdObj.value.email,
        code: forgetPwdObj.value.code,
        newPassword: forgetPwdObj.value.newPassword
      });

      ElMessage.success('密码重置成功，请登录');
      forgetPwdDialogVisible.value = false;
      if (codeTimer.value) {
        clearInterval(codeTimer.value);
      }
    } catch (error) {
      ElMessage.error(error.message || '密码重置失败');
    }
  });
};

// 登录表单数据
const user = ref({
  username: '',
  password: '',
  captcha: '',
  key: ''
});

// 注册弹窗相关变量
const registerDialogVisible = ref(false);
const registerObj = ref({
  username: '',
  password: '',
  confirmPwd: '',
  uimg: '',
  roleid: 1, // 角色ID默认设为1（普通用户）
  phone: '',
  email: '',
  name: '', // 新增姓名字段
  gender: ''
});
const registerFormRef = ref(null);

// 注册表单验证规则
const registerRules = ref({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 1, max: 16, message: '用户名长度需在1-16位之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度需在6-20位之间', trigger: 'blur' }
  ],
  confirmPwd: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerObj.value.password) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  phone: [
    { required: false, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/, message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  name: [
    { required: false, message: '请输入姓名', trigger: 'blur' },
    { min: 1, max: 20, message: '姓名长度需在1-20位之间', trigger: 'blur' }
  ]
});

// 页面初始化
onMounted(async () => {
  localStorage.removeItem('token');
  loadCaptcha();
  document.body.classList.add('loaded');
})

const router = useRouter();
const captcha = ref("");
const loading = ref(false);

// 登录提交
const onSubmit = async () => {
  if (!user.value.username || !user.value.password || !user.value.captcha) {
    ElMessage.warning('请完整填写登录信息');
    return;
  }

  loading.value = true;
  try {
    const res = await loginApi.login(user.value);
    if (res) {
      localStorage.setItem('token', res);
      document.querySelector('.login-card').classList.add('login-success');
      setTimeout(() => router.push("/seat"), 600);
    }
  } catch (error) {
    ElMessage.error(error.message || '登录失败，请检查信息');
    loadCaptcha(); // 登录失败刷新验证码
  } finally {
    loading.value = false;
  }
}

// 加载验证码
const loadCaptcha = async () => {
  try {
    const res = await loginApi.captcha();
    user.value.key = res.key;
    const captchaImg = document.querySelector('.img-verCode');
    captchaImg.classList.add('refreshing');
    setTimeout(() => {
      captcha.value = res.base;
      captchaImg.classList.remove('refreshing');
    }, 200);
  } catch (error) {
    ElMessage.error('验证码加载失败，请重试');
  }
}

// 打开注册弹窗
const openRegisterDialog = () => {
  registerObj.value = {
    username: '',
    password: '',
    confirmPwd: '',
    uimg: '',
    roleid: 1, // 默认普通用户
    phone: '',
    email: '',
    name: '',
    gender: ''
  };
  registerDialogVisible.value = true;
};

// 注册提交
const submitRegister = async () => {
  if (!registerFormRef.value) return;
  registerFormRef.value.validate(async (valid) => {
    if (!valid) return;
    try {
      // 移除确认密码字段，准备提交
      const submitData = { ...registerObj.value };
      delete submitData.confirmPwd;
      await loginApi.add(submitData);
      ElMessage.success('注册成功，请登录');
      registerDialogVisible.value = false;
    } catch (err) {
      ElMessage.error(err.message || '注册失败，请重试');
    }
  });
};

// 注册头像上传成功处理
const handleRegisterUploadSuccess = (response) => {
  registerObj.value.uimg = response.data;
};

</script>


<template>
  <div class="login-container">
    <!-- 登录卡片 -->
    <div class="login-card">
      <!-- 品牌区域 -->
      <div class="brand-section">
        <div class="logo-container">
          <img src="@/assets/logo.png" alt="羽速抢票系统logo" class="logo" />
        </div>
        <div class="brand-title">
          <h1>羽速抢票</h1>
          <p class="system-desc">羽毛球比赛抢票系统</p>
        </div>
      </div>

      <!-- 登录表单 -->
      <el-form class="login-form" :model="user" size="large">
        <el-form-item>
          <el-input
              v-model="user.username"
              placeholder="请输入用户名"
              :prefix-icon="User"
              maxlength="16"
              class="custom-input"
              autocomplete="off">
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-input
              v-model="user.password"
              placeholder="请输入密码"
              show-password
              :prefix-icon="Lock"
              maxlength="16"
              class="custom-input"
              autocomplete="off">
          </el-input>
        </el-form-item>

        <el-form-item>
          <div class="captcha-container">
            <el-input
                v-model="user.captcha"
                placeholder="验证码"
                :prefix-icon="Key"
                maxlength="5"
                class="captcha-input"
                autocomplete="off">
            </el-input>
            <img
                :src="captcha"
                class="img-verCode"
                @click="loadCaptcha"
                alt="验证码，点击刷新">
          </div>
        </el-form-item>

        <el-form-item>
          <el-button
              class="login-btn"
              type="primary"
              @click="onSubmit"
              :loading="loading">
            登录
            <ArrowRight class="login-arrow" />
          </el-button>
        </el-form-item>

        <div class="login-footer">
          <a href="javascript:void(0)" class="link-item" @click="openForgetPwdDialog">忘记密码?</a>
          <el-button
              type="text"
              class="link-item"
              @click="openRegisterDialog"
          >
            注册账号
          </el-button>
        </div>
      </el-form>
    </div>

    <!-- 页脚信息 -->
    <footer class="login-footer-info">
      <p>© 2025 羽速抢票-羽毛球比赛抢票系统 版权所有</p>
    </footer>
  </div>

  <!-- 注册弹窗 -->
  <el-dialog
      v-model="registerDialogVisible"
      title="用户注册"
      width="500px"
      :close-on-click-modal="false"
  >
    <el-form
        ref="registerFormRef"
        :model="registerObj"
        :rules="registerRules"
        label-width="100px"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="registerObj.username" placeholder="请输入用户名" autocomplete="off" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="registerObj.password" type="password" placeholder="请输入密码" autocomplete="off" />
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPwd">
        <el-input v-model="registerObj.confirmPwd" type="password" placeholder="请再次输入密码" autocomplete="off" />
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input v-model="registerObj.name" placeholder="请输入姓名" autocomplete="off" />
      </el-form-item>
      <el-form-item label="头像">
        <el-upload
            class="avatar-uploader"
            action="/api/upload/file"
            :show-file-list="false"
            :on-success="handleRegisterUploadSuccess"
        >
          <img
              :src="registerObj.uimg ? registerObj.uimg : 'https://xrysitu.oss-cn-beijing.aliyuncs.com/b5a24a51-5db3-40ec-bffc-8999e9cfafc3.png'"
              style="width: 100px; height: 100px; border-radius: 50%; object-fit: cover"
              alt="用户头像"
          />
        </el-upload>
      </el-form-item>
      <!-- 角色选择（默认1且不可修改） -->
      <el-form-item label="角色">
        <el-select v-model="registerObj.roleid" disabled style="width: 100%">
          <el-option
              :label="registerObj.roleid === 0 ? '管理员' : '普通用户'"
              :value="registerObj.roleid"
          />
        </el-select>
        <div style="font-size: 12px; color: #666; margin-top: 5px">
          注册用户默认分配普通用户角色
        </div>
      </el-form-item>
      <el-form-item label="性别">
        <el-input v-model="registerObj.gender" placeholder="请输入性别（男/女）" autocomplete="off" />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="registerObj.phone" placeholder="请输入手机号" autocomplete="off" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="registerObj.email" placeholder="请输入邮箱" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="registerDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitRegister">确认注册</el-button>
    </template>
  </el-dialog>

  <!-- 忘记密码弹窗 -->
  <el-dialog
      v-model="forgetPwdDialogVisible"
      title="忘记密码"
      width="500px"
      :close-on-click-modal="false"
  >
    <el-form
        ref="forgetPwdFormRef"
        :model="forgetPwdObj"
        :rules="forgetPwdRules"
        label-width="100px"
    >
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="forgetPwdObj.email" placeholder="请输入注册邮箱" autocomplete="off" />
      </el-form-item>

      <el-form-item label="验证码" prop="code">
        <el-row :gutter="10">
          <el-col :span="16">
            <el-input v-model="forgetPwdObj.code" placeholder="请输入验证码" autocomplete="off" />
          </el-col>
          <el-col :span="8">
            <el-button
                type="primary"
                @click="sendVerificationCode"
                :disabled="codeCountdown > 0"
            >
              {{ codeCountdown > 0 ? `${codeCountdown}s后重发` : '发送验证码' }}
            </el-button>
          </el-col>
        </el-row>
      </el-form-item>

      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="forgetPwdObj.newPassword" type="password" placeholder="请输入新密码" autocomplete="off" />
      </el-form-item>

      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input v-model="forgetPwdObj.confirmPassword" type="password" placeholder="请再次输入新密码" autocomplete="off" />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="forgetPwdDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="confirmResetPwd">确认重置</el-button>
    </template>
  </el-dialog>

</template>

<style scoped>
/* 基础容器样式 */
.login-container {
  min-height: 100vh;
  position: relative;
  overflow: hidden;
  background-image: url('@/assets/back.png');
  background-repeat: no-repeat;
  background-position: center;
  background-attachment: fixed;
  background-size: cover;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 20px;
  /* 渐变叠加增强可读性 */
  &::before {
    content: '';
    position: absolute;
    inset: 0;
    background: linear-gradient(135deg, rgba(255,255,255,0.8) 0%, rgba(255,255,255,0.9) 100%);
    z-index: 0;
  }
}

/* 登录卡片 */
.login-card {
  width: 100%;
  max-width: 420px;
  background-color: rgba(255,255,255,0.92);
  border-radius: 16px;
  box-shadow: 0 10px 30px rgba(255, 105, 180, 0.15);
  overflow: hidden;
  position: relative;
  z-index: 1;
  transition: all 0.3s ease;
  backdrop-filter: blur(8px);
  -webkit-backdrop-filter: blur(8px);

  &:hover {
    box-shadow: 0 15px 35px rgba(255, 105, 180, 0.2);
    transform: translateY(-5px);
  }
}

/* 品牌区域 */
.brand-section {
  background: linear-gradient(135deg, #FF69B4 0%, #FF85B3 100%);
  padding: 30px 20px;
  display: flex;
  align-items: center;
  gap: 15px;

  .logo-container {
    width: 60px;
    height: 60px;
    background-color: #fff;
    border-radius: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 4px 12px rgba(255, 105, 180, 0.2);

    .logo {
      width: 100%;
      height: 100%;
      object-fit:  cover;
    }
  }

  .brand-title {
    h1 {
      color: #fff;
      font-size: 26px;
      margin: 0 0 5px 0;
      font-weight: 600;
      text-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }

    .system-desc {
      color: rgba(255,255,255,0.9);
      font-size: 14px;
      margin: 0;
      text-shadow: 0 1px 2px rgba(0,0,0,0.1);
    }
  }
}

/* 登录表单 */
.login-form {
  padding: 30px 25px;

  .custom-input {
    border-radius: 8px;
    border-color: #ffcceb;
    transition: all 0.3s ease;

    &:focus-within {
      border-color: #FF69B4;
      box-shadow: 0 0 0 3px rgba(255, 105, 180, 0.15);
    }
  }
}

/* 验证码区域 */
.captcha-container {
  display: flex;
  gap: 10px;

  .captcha-input {
    flex: 1;
    border-radius: 8px;
    border-color: #ffcceb;
  }

  .img-verCode {
    width: 100px;
    height: 40px;
    border-radius: 8px;
    cursor: pointer;
    object-fit: cover;
    transition: all 0.2s ease;
    border: 1px solid #ffcceb;

    &:hover {
      transform: scale(1.02);
    }

    &.refreshing {
      opacity: 0.6;
      transform: rotate(10deg);
    }
  }
}

/* 登录按钮 */
.login-btn {
  width: 100%;
  height: 45px;
  border-radius: 8px;
  background: linear-gradient(135deg, #FF69B4 0%, #FF85B3 100%);
  border: none;
  font-size: 16px;
  font-weight: 500;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;

  &:hover {
    background: linear-gradient(135deg, #FF5CA8 0%, #FF69B4 100%);
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(255, 105, 180, 0.3);
  }

  &:active {
    transform: translateY(0);
  }

  .login-arrow {
    transition: transform 0.3s ease;
  }

  &:hover .login-arrow {
    transform: translateX(3px);
  }
}

/* 表单底部链接 */
.login-footer {
  display: flex;
  justify-content: space-between;
  margin-top: 15px;

  .link-item {
    color: #FF69B4;
    font-size: 14px;
    text-decoration: none;
    transition: color 0.2s ease;

    &:hover {
      color: #FF5CA8;
      text-decoration: underline;
    }
  }
}

/* 注册按钮样式调整 */
.link-item.el-button--text {
  color: #FF69B4;
  padding: 0;
  height: auto;
  font-size: 14px;

  &:hover {
    color: #FF5CA8;
    text-decoration: underline;
    background: transparent;
  }
}

/* 页脚信息 */
.login-footer-info {
  margin-top: 30px;
  color: #888;
  font-size: 12px;
  text-align: center;
  position: relative;
  z-index: 1;
}

/* 登录成功动画 */
.login-success {
  animation: loginSuccess 0.6s ease forwards;
}

@keyframes loginSuccess {
  0% {
    transform: scale(1);
    opacity: 1;
  }
  50% {
    transform: scale(1.05);
    opacity: 0.8;
  }
  100% {
    transform: scale(0);
    opacity: 0;
  }
}

/* 页面加载动画 */
body {
  opacity: 0;
  transition: opacity 0.5s ease;
}

body.loaded {
  opacity: 1;
}

/* 注册弹窗样式补充 */
:deep(.avatar-uploader) {
  display: inline-block;
  cursor: pointer;
}

:deep(.el-select.is-disabled .el-select__input) {
  color: #333;
}

/* 响应式调整 */
@media (max-width: 480px) {
  .login-card {
    width: 100%;
    margin: 0 10px;
  }

  .brand-section {
    padding: 25px 15px;
  }

  .login-form {
    padding: 25px 20px;
  }
}

/* 粉色主题按钮样式 */
:deep(.el-button--primary) {
  background-color: #FF69B4 !important;
  border-color: #FF69B4 !important;
  &:hover {
    background-color: #FF5CA8 !important;
    border-color: #FF5CA8 !important;
  }
}
</style>